<template>
  <t-dialog :header="getHeader" :visible.sync="visible" :onClose="closeDialog" :closeOnOverlayClick="false"
    :confirmBtn="null" width="90%" top="5%" v-if="isDialog">
    <t-sticky-tool v-if="!hideInfo" :style="{ position: 'absolute', overflow: 'hidden', zIndex: 1000 }"
      :offset="[-50, 60]" @click="createPDF(1)">
      <!-- <t-sticky-item label="导出PDF">
        <template #icon>
          <t-icon name="file-pdf"></t-icon>
        </template>
</t-sticky-item> -->
    </t-sticky-tool>
    <current-project-detail :objId="objId" :hideByProjectType="hideByProjectType" :reviewOpen="reviewOpen"
      :hideInfo="hideInfo"></current-project-detail>
  </t-dialog>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import FileUpload from "@/components/FileUpload/index.vue"
import InnerHtml from "@/components/InnerHtml/index.vue";
import { getFiles } from "@/api/common";
import dayjs from "dayjs";


import currentProjectDetail from "./current-project-detail.vue";

export default {
  name: "project-detail",
  dicts: ["project_type", "subject_classification", "sys_user_sex", "prof_tit", "degree", "duty", "platform_type", "member_type", "expect_result_type", "education"],
  components: {
    FileUpload,
    InnerHtml,
    currentProjectDetail
  },
  props: {
    objId: [String, Number],
    approveType: String,
    // header: String,
    isDialog: {
      type: Boolean,
      default: true
    },
    row: Object,
    hideInfo: {
      type: Boolean,
      default: false
    },
    hideByProjectType: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'large'
    },
    reviewOpen: {
      type: Boolean,
      default: false
    },
    isReview: {
      type: Boolean,
      default: false
    },
    tabDefaultValue: {
      type: String,
      default: '1'
    }
  },
  data () {
    return {
      file_domain: VITE_FILE_DOMAIN,
      expresswayOptions: [],
      isMyProject: false,
      openDG: false,
      openRWS: false,
      openYS: false,
      stepValue: this.tabDefaultValue,
      header: '',
      dgHeader: '',
      rwsHeader: '',
      fundingObj: { subsidyFunding: 0, adviceFunding: 0 },
      disableDate: {},
      profTitOptions: [],
      expectedResultsColumns: [
        {
          colKey: "sort",
          title: "序号",
          width: 64,
          align: "center",
        },
        {
          colKey: "expectResultTypeLabel",
          title: "成果类型",
          align: "center",
        },
        {
          colKey: "count",
          title: "数量",
          align: "center",
        },
      ],
      site_tag: import.meta.env.VITE_SITE_TAG,
      visible: true,
      tabValue: "1",
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },
        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "附件列表",
          align: "left",
        },
      ],
      projectFileData: [
        {
          id: 1,
          c1: "查新报告",
          c2: "是",
          moduleKey: "projectCXBG",
          fileIds: [],
          fileLists: [],
        },
        {
          id: 2,
          c1: "归口管理单位科研诚信承诺书(模版)",
          c2: "是",
          c3: 'view/模板/归口管理单位科研诚信承诺书.pdf',
          fileIds: [],
          fileLists: [],
          moduleKey: "projectCNS"
        },
        {
          id: 3,
          c1: "项目组科研诚信承诺书(模版)",
          c2: "是",
          c3: 'view/模板/项目组科研诚信承诺书.pdf',
          fileIds: [],
          fileLists: [],
          moduleKey: "projectTeamCNS"
        },
        {
          id: 4,
          c1: "已盖章申报书",
          c2: "所有申报流程审批通过后，从系统导出PDF线下盖章(申报用户上传)",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectSBS"
        },
        {
          id: 6,
          c1: "其他",
          c2: "否",
          moduleKey: "projectQT",
          fileIds: [],
          fileLists: [],
          require: false,
        },
      ],
      data: {
        projectCategory: '',
        projectTeam: {},
        projectLeader: {},
        projectLinker: {},
        projectBackground: {
          background: ''
        },
        projectApproach: {
          projectExpectResults: []
        },
        projectBasicstudy: {},
        projectCompanyList: [],
        projectMembers: [],
        projectBudget: {},
        deptName: '',
        sysExpressway: {
          code: '',
          startNum: '',
          endNum: '',
        }
      },
      projectCategoryOptions: []
    }
  },
  computed: {
    getHeader () {
      let header = ''
      if (this.rwsHeader) {
        header = this.rwsHeader
      }
      if (this.dgHeader && !this.rwsHeader) {
        header = this.dgHeader
      }
      if (this.header && !this.rwsHeader && !this.dgHeader) {
        header = this.header
      }
      return header
    }
  },
  methods: {
    createPDF (type) {
      const instance = this.$loading({
        fullscreen: true,
        attach: 'body',
        preventScrollThrough: false,
      });
      if (type === 1) {
        this.$api.kjxm.project.projectTestPDF(this.objId).then(response => {
          window.open(response.data.fullFilePath, '_blank')
          instance.hide();
        }).catch((e) => {
          instance.hide();
          this.$message.error(e.toString());
        });
      } else if (type === 2) {
        this.$api.kjxm.outline.createPDF(this.objId, this.isReview ? 2 : 1).then(response => {
          window.open(response.data.fullFilePath, '_blank')
          instance.hide();
        }).catch((e) => {
          instance.hide();
          this.$message.error(e.toString());
        });
      } else if (type === 3) {
        this.$api.kjxm.contract.createPDF(this.objId, this.isReview ? 2 : 1).then(response => {
          window.open(response.data.fullFilePath, '_blank')
          instance.hide();
        }).catch((e) => {
          instance.hide();
          this.$message.error(e.toString());
        });
      }

    },
    uploadSuccess (ids) {
      this.$api.kjxm.threeProject.edit({
        id: this.objId,
        sysAttMainVo: {
          sysAttMainIds: ids,
        }
      }).then(val => {
        this.$message.success("上传成功");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    async getObj () {
      Promise.all([this.getDeclareTree(), this.getprofTitTreeSelect(), this.getExpresswayTreeSelect()]);
      if (this.hideInfo) {
        this.$api.kjxm.threeProject.getAllHide(this.objId).then(response => {
          this.header = response.data.projectName;
          const isMyProject = this.$store.state.user.userId === response.data.createUserId;
          // const isProjectSBS = isOwner && Number(response.data.projectStatus || 0)>=6 && Number(response.data.projectStatus || 0)!==7;
          // 从单位里面找出承担单位
          // const companyData = response.data.projectCompanyList.filter((val) => val.type === '1');
          // if(companyData.length>0){
          //   this.data.deptName = companyData[0].name;
          // }
          response.data.projectMembers = response.data.projectMembers || []
          this.disableDate = {
            before: dayjs(response.data.startDate, "YYYY-MM-DD").endOf('month').subtract(1, 'month').format(),
            after: dayjs(response.data.endDate, "YYYY-MM-DD").endOf('month').subtract(0, 'month').format(),
          }
          this.fundingObj = {
            adviceFunding: response.data.adviceFunding,
            subsidyFunding: response.data.subsidyFunding
          }
          Object.assign(this.data, response.data)
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else {
        this.$api.kjxm.threeProject.get(this.objId).then(response => {
          if (response.data.createUserId === Number(this.$store.state.user.userId)) {
            this.isMyProject = true;
          }
          this.header = response.data.projectName;
          const isOwner = this.$store.state.user.userId === response.data.createUserId;
          // const isProjectSBS = Number(response.data.projectStatus || 0)>=6 && Number(response.data.projectStatus || 0)!==7;
          // 从单位里面找出承担单位
          // const companyData = response.data.projectCompanyList.filter((val) => val.type === '1');
          // if(companyData.length>0){
          //   this.data.deptName = companyData[0].name;
          // }




          response.data.projectMembers = response.data.projectMembers || []
          this.disableDate = {
            before: dayjs(response.data.startDate, "YYYY-MM-DD").endOf('month').subtract(1, 'month').format(),
            after: dayjs(response.data.endDate, "YYYY-MM-DD").endOf('month').subtract(0, 'month').format(),
          }
          this.fundingObj = {
            adviceFunding: response.data.adviceFunding,
            subsidyFunding: response.data.subsidyFunding
          }
          Object.assign(this.data, response.data)
          // 如果是高速公路项目
          if (this.data.isRoadProject === '1') {

          }




          // 获取项目附件
          getFiles(this.objId).then((res) => {
            const files = {}
            res.data.forEach((item) => {
              if (!files[item.moduleKey]) {
                files[item.moduleKey] = []
              }
              files[item.moduleKey].push({
                name: item.fileName,
                url: item.fullFilePath,
                id: item.id,
                filePath: item.filePath
              })
            })
            // this.projectFileData[0].fileLists = files.projectCXBG || [];
            // this.projectFileData[1].fileLists = files.projectCNS || [];
            // this.projectFileData[2].fileLists = files.projectTeamCNS || [];
            // // this.projectFileData[3].fileLists = files.projectSBS || [];
            // this.projectFileData[0].fileIds = files.projectCXBG?.map(val => val.id) || [];
            // this.projectFileData[1].fileIds = files.projectCNS?.map(val => val.id) || [];
            // this.projectFileData[2].fileIds = files.projectTeamCNS?.map(val => val.id) || [];
            // // this.projectFileData[3].fileIds = files.projectSBS?.map(val => val.id) || [];
            // // if(isProjectSBS){
            // //
            // // }
            // this.projectFileData[3].fileLists = files.projectSBS || [];
            // this.projectFileData[3].fileIds = files.projectSBS?.map(val => val.id) || [];
            this.projectFileData.forEach((val, index) => {
              this.projectFileData[index].fileLists = files[val.moduleKey] || [];
              this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
            })
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },
    getDeclareTree () {
      return this.$api.kjxm.project.planCategoryTree().then(response => {
        this.projectCategoryOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getExpresswayTreeSelect () {
      return this.$api.system.expressway.treeSelect().then(
        (res) => {
          this.expresswayOptions = res.data;
        }).catch((e) => {
          this.$message.error(e.toString());
        });
    },
    getprofTitTreeSelect () {
      return this.$api.system.profTit.treeselect().then(response => {
        this.profTitOptions = response.data;
        // this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    closeDialog () {
      this.$emit("update:visible", false);
    },
  }
}
</script>

<style lang="less" scoped>
.t-tab-panel {
  padding: 10px;
}

.tab-panel {
  height: calc(65vh - 64px);
  overflow: scroll;
}

.tab-full-panel {
  height: calc(80vh - 64px);
  overflow: scroll;
}

.t-form__item {
  margin-bottom: 6px
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}

.content_style {
  font-size: 12pt;
  font-family: 宋体;
  line-height: 1.5;
}
</style>
